#define _CRT_SECURE_NO_WARNINGS 1

#include "Seqlist.h"

void SLInit(SL* psl)
{
	psl->a = NULL;
	psl->capacity = psl->size = 0;
}

void SLDestroy(SL* psl)
{
	assert(psl->a);
	free(psl->a);
	psl->a = NULL;
	psl->capacity = psl->size = 0;
}

void SLCheckCapacity(SL* psl)
{
	if (psl->size == psl->capacity)
	{
		int newcapacity = psl->capacity == 0 ? 4 : psl->capacity * 2;
		SLDateType* tmp = (SLDateType*)realloc(psl, sizeof(SLDateType) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		psl->a = tmp;
		psl->capacity = newcapacity;
	}
}

void SLInsert(SL* psl, int pos, SLDateType x)
{
	assert(psl);
	assert(pos >= 0 && pos <= psl->size);
	SLCheckCapacity(psl);
	int end = psl->size - 1;
	while (end >= pos)
	{
		psl->a[end + 1] = psl->a[end];
		end--;
	}
	psl->a[pos] = x;
	psl->size++;
}

void SLErase(SL* psl, int pos)
{
	assert(psl);
	assert(pos >= 0 && pos < psl->size);
	int start = pos + 1;
	while (start < psl->size)
	{
		psl->a[start - 1] = psl->a[start];
		start++;
	}
	psl->size--;
}

void SLPushBack(SL* psl, SLDateType x)
{
	assert(psl);
	//SLCheckCapacity(psl);
	SLInsert(psl, psl->size, x);
	//psl->size++;
}

void SLPushFront(SL* psl, SLDateType x)
{
	assert(psl);
	SLInsert(psl, 0, x);
}

void SLPopBack(SL* psl)
{
	assert(psl);
	SLErase(psl, psl->size - 1);
}

void SlpopFront(SL* psl)
{
	assert(psl);
	SLErase(psl, 0);
}

int SLFind(SL* psl, SLDateType x)
{
	assert(psl);
	for (int i = 0; i < psl->size; i++)
	{
		if (psl->a[i] = x)
		{
			return i;
		}
	}
	return -1;
}

void SLModify(SL* psl, int pos, SLDateType x)
{
	assert(psl);
	assert(pos >= 0 && pos < psl->size);
	psl->a[pos] = x;
}